import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { Theme } from '@/types'


export const useAppStore = defineStore('app', () => {
  // 状态
  const theme = ref<Theme>('dark')
  const sidebarCollapsed = ref(false)
  const language = ref('zh-CN')
  const loading = ref(false)

  // Getters
  const isDarkMode = computed(() => theme.value === 'dark')

  // Actions
  const setTheme = (newTheme: Theme) => {
    theme.value = newTheme
    // 更新 HTML 类名以支持主题切换
    document.documentElement.className = newTheme
    // 保存到本地存储
    localStorage.setItem('app-theme', newTheme)
  }

  const toggleSidebar = () => {
    sidebarCollapsed.value = !sidebarCollapsed.value
    localStorage.setItem('sidebar-collapsed', String(sidebarCollapsed.value))
  }

  const setLanguage = (newLanguage: string) => {
    language.value = newLanguage
    localStorage.setItem('app-language', newLanguage)
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  // 初始化应用状态
  const initializeApp = () => {
    // 恢复主题设置
    const savedTheme = localStorage.getItem('app-theme') as Theme
    if (savedTheme && ['light', 'dark', 'auto'].includes(savedTheme)) {
      setTheme(savedTheme)
    }

    // 恢复侧边栏状态
    const savedSidebarState = localStorage.getItem('sidebar-collapsed')
    if (savedSidebarState) {
      sidebarCollapsed.value = savedSidebarState === 'true'
    }

    // 恢复语言设置
    const savedLanguage = localStorage.getItem('app-language')
    if (savedLanguage) {
      language.value = savedLanguage
    }
  }

  // 重置应用状态
  const resetAppState = () => {
    theme.value = 'dark'
    sidebarCollapsed.value = false
    language.value = 'zh-CN'
    loading.value = false
    
    // 清除本地存储
    localStorage.removeItem('app-theme')
    localStorage.removeItem('sidebar-collapsed')
    localStorage.removeItem('app-language')
  }

  return {
    // State
    theme,
    sidebarCollapsed,
    language,
    loading,

    // Getters
    isDarkMode,

    // Actions
    setTheme,
    toggleSidebar,
    setLanguage,
    setLoading,
    initializeApp,
    resetAppState
  }
})